package com.lcb.manager.web;

import com.alibaba.fastjson.JSON;
import com.lcb.manager.entity.Person;
import com.lcb.manager.repository.PersonRepository;
import com.lcb.manager.vo.Json;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.sql.Date;

@Controller
@RequestMapping(value = "/crime")
public class CrimeController {

    @Autowired
    private PersonRepository personRepository;

    @RequestMapping(value = "/get_form")
    public String getCrimeInfoForm(Model model, @RequestParam int id) {
        Person person = personRepository.findById(id).orElse(null);
        model.addAttribute("title", "犯罪信息");
        model.addAttribute("isEdit", true);
        if (person != null) {
            model.addAttribute("vo", person);
        }
        return "_crime_info_form";
    }

    @ResponseBody
    @PostMapping("/edit")
    public String editCrimeInfo(
            @RequestParam("id") int id,
            @RequestParam("crimeTime") String crimeTime,
            @RequestParam("crimeType") String crimeType,
            @RequestParam("crimeDetail") String crimeDetail) throws IOException {
        Json result = new Json();

        Person person = personRepository.findById(id).orElse(null);
        if (person != null) {
            person.setCrimeTime(Date.valueOf(crimeTime));
            person.setCrimeType(crimeType);
            person.setCrimeDetail(crimeDetail);
            personRepository.save(person);
        }
        result.code = 0;
        result.msg = "提交成功！";
        return JSON.toJSONString(result);
    }
}
